import React from 'react'
import F from 'lodash/fp'
import { connect } from 'react-redux'
import { contentChange, selectElm, replaceImgOpen, markEditable, deleteElm, $cropperModal, unMarkEditable } from '../actions/content-change'
import { analysisSvg } from '../utils.js'

const isImgElm = elm => /<img|<xtb-svg/.test(elm.content)

const parseSrc = content => content.match(/<img\s+.*?src="(.*?)"/)[1]

const ImgElm = ({ content, onClick, selected, replaceImg, classes }) => {
    return (
        <div className={"layer-item " + classes.join(' ')} >
            <div className={selected ? "layer-item-c layer-item-select" : "layer-item-c"} onClick={onClick}>
                {/<xtb-svg/.test(content) ? <div dangerouslySetInnerHTML={{ __html: content }} /> : <img src={parseSrc(content)} />}
            </div>
            <button
                className="layer-change"
                onClick={replaceImg}
            >
                替换
            </button>
        </div>
    )
}

class UserLayer extends React.Component {
    componentDidMount() {
        $('#layer-wp-tab').tabs({ noSwipe: 1 })
    }

    render() {
        const { activeIndex, elements, markEditable, mode, selectedPath } = this.props

        let [imgs, txts] = F.partition(isImgElm, elements.filter(t => t).map((t, i) => ({ content: t.content, index: i, selected: t.selected, classes: t.classes })))

        if (mode === 'card') imgs = imgs.filter(t => t.classes.includes('user-editable'))
        return (
            <div className="am-tabs">
                {imgs.map(t => <ImgElm
                    key={t.index}
                    selected={selectedPath.includes(`${activeIndex}.${t.index}`)}
                    content={t.content}
                    replaceImg={() => this.props.replaceImgOpen([activeIndex, t.index], elements)}
                    onClick={ev => this.props.selectElm([activeIndex, t.index], ev.ctrlKey)}
                    classes={t.classes}
                />)}
            </div>
        )
    }
}



module.exports = connect(
    ({ card: state, mode }) => ({
        elements: state.pages[state.activeIndex] ? state.pages[state.activeIndex].elements : [],
        activeIndex: state.activeIndex,
        selectedPath: state.selectedPath,
        mode
    })
    , (dispatch, props) => ({
        selectElm: F.compose(dispatch, selectElm),

        replaceImgOpen: (path) => {
            dispatch(selectElm(path, false, true))
            props.$gallery.modal({ closeViaDimmer: false })
            dispatch($cropperModal(props.$cropper))
        },

        markEditable: F.compose(dispatch, markEditable),
        unMark: F.compose(dispatch, unMarkEditable),
        deleteElm: function (e) {
            layer.confirm('你确定要删除吗？', function (index) {
                F.compose(dispatch, deleteElm)(e)
                layer.close(index)
            })
        }
    })
)(UserLayer)